package seg.tef4.whms.activity;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.device.scanner.configuration.Triggering;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.scan.R;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import seg.tef4.whms.activity.activityinit.SubBaseActivity;
import seg.tef4.whms.apis.EquipmentApi;
import seg.tef4.whms.apis.OutWarehouseApi;
import seg.tef4.whms.apis.SparePartApi;
import seg.tef4.whms.component.OutWarehouseRecycleView;
import seg.tef4.whms.domain.TOutWarehouse;
import seg.tef4.whms.domain.TOutWarehouseV;
import seg.tef4.whms.domain.TSparePart;
import seg.tef4.whms.domain.entity.SysUser;
import seg.tef4.whms.util.auth.OnlineUser;
import seg.tef4.whms.util.dialog.AlertDialogCreator;
import seg.tef4.whms.util.retrofitutil.RetrofitUtil;

public class OutScanActivity extends SubBaseActivity {
    private ImageView scanButton;
    private TextView barcode_result;

    private ScanManager mScanManager;
    int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
    int[] idmodebuf = new int[]{PropertyID.WEDGE_KEYBOARD_ENABLE, PropertyID.TRIGGERING_MODES, PropertyID.LABEL_APPEND_ENTER};
    String[] action_value_buf = new String[]{ScanManager.ACTION_DECODE, ScanManager.BARCODE_STRING_TAG};
    int[] idmode;

    // 备件信息
    private TextView name;
    private TextView brand;
    private TextView line;
    private TextView station;
    private TextView location;
    private TextView specification;
    private TextView stock;
    private TextView unitPrice;

    private LinearLayout controller;

    private Spinner line_spinner;
    private Spinner station_spinner;
    private Spinner out_type_spinner;

    private EditText out_number;

    private Button button;

    private boolean uboxunMark = false;

    private SparePartApi sparePartApi = (SparePartApi) RetrofitUtil.getApiInstance(SparePartApi.class);

    private EquipmentApi equipmentApi = (EquipmentApi)  RetrofitUtil.getApiInstance(EquipmentApi.class);

    private OutWarehouseApi outWarehouseApi = (OutWarehouseApi)  RetrofitUtil.getApiInstance(OutWarehouseApi.class);

    private BroadcastReceiver mScanReceiver;

    private void reset(){
        controller.setVisibility(View.INVISIBLE);
        name.setText("");
        brand.setText("");
        line.setText("");
        station.setText("");
        location.setText("");
        specification.setText("");
        stock.setText("");
        unitPrice.setText("");
        line_spinner.setSelection(0);
        station_spinner.setSelection(0);
        out_type_spinner.setSelection(0);
        out_number.setText("");
    }


    public static void startOutScanActivity(Context context) {
        context.startActivity(new Intent(context, OutScanActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out_scan);

        // 备件
        name = findViewById(R.id.name);
        brand = findViewById(R.id.brand);
        line = findViewById(R.id.line);
        station = findViewById(R.id.station);
        location = findViewById(R.id.location);
        specification =  findViewById(R.id.specification);
        stock = findViewById(R.id.stock);
        unitPrice= findViewById(R.id.unitPrice);
        controller= findViewById(R.id.controller);

        line_spinner = findViewById(R.id.line_spinner);
        station_spinner = findViewById(R.id.station_spinner);
        out_type_spinner = findViewById(R.id.out_type_spinner);
        out_number = findViewById(R.id.out_number);
        button = findViewById(R.id.button);

        barcode_result = findViewById(R.id.barcode_result);
        scanButton = findViewById(R.id.scanButton);

        spinnerInit();


        try {
            mScanManager = new ScanManager();
            mScanManager.openScanner();
            uboxunScanInit();
            uboxunMark = true;
        }catch (Exception e){
            PhoneScanInit();
        }






        button.setOnClickListener(view -> {
            String materialNo = this.barcode_result.getText().toString();
            if(materialNo == null || materialNo.trim().equals(""))
                materialNo = null;
            String line = this.line_spinner.getSelectedItem() == null ?
                    null : this.line_spinner.getSelectedItem().toString();
            if(line !=null && line.equals("【请选择】"))
                line = null;
            String station = this.station_spinner.getSelectedItem() == null ?
                    null : this.station_spinner.getSelectedItem().toString();
            if(station!=null && station.equals("【请选择】"))
                station = null;
            else
                station = station.split("\n")[0];
            String out_type = this.out_type_spinner.getSelectedItem() == null ?
                    null : this.out_type_spinner.getSelectedItem().toString();
            if(out_type!=null && out_type.equals("【请选择】"))
                out_type = null;
            String outNumber = this.out_number.getText().toString();
            if(outNumber == null || outNumber.trim().equals(""))
                outNumber = null;

            TOutWarehouseV tOutWarehouseV = new TOutWarehouseV();
            tOutWarehouseV.setMaterialNo(materialNo);
            tOutWarehouseV.setLine(line);
            tOutWarehouseV.setStation(station);
            tOutWarehouseV.setOutType(out_type);
            tOutWarehouseV.setCreateBy(OnlineUser.getSysUser().getUserName());
            if(outNumber !=null)
                tOutWarehouseV.setOutNum(Long.parseLong(outNumber));

            out(tOutWarehouseV);
        });


    }

    @SuppressLint("ClickableViewAccessibility")
    private void PhoneScanInit(){
        scanButton.setOnClickListener(v -> {
            IntentIntegrator integrator = new IntentIntegrator(OutScanActivity.this);
            // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
            integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
            integrator.setCaptureActivity(ScanActivity.class); //设置打开摄像头的Activity
            integrator.setPrompt("请扫描ISBN"); //底部的提示文字，设为""可以置空
            integrator.setCameraId(0); //前置或者后置摄像头
            integrator.setBeepEnabled(true); //扫描成功的「哔哔」声，默认开启
            integrator.setBarcodeImageEnabled(true);
            integrator.initiateScan();
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            String result = scanResult.getContents();
            barcode_result.setText(result);
            setScanResult(result);

        }
    }

    /**
     * @description 优博讯初始化
     */
    @SuppressLint("ClickableViewAccessibility")
    private void uboxunScanInit(){
        action_value_buf = mScanManager.getParameterString(idbuf);
        idmode = mScanManager.getParameterInts(idmodebuf);
        idmode[0] = 0;
        mScanReceiver= new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String result = intent.getStringExtra(action_value_buf[1]);
                setScanResult(result);
            }

        };
        scanButton.setOnTouchListener((v, event) -> {
            final int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    if(idmode[1] == Triggering.CONTINUOUS.toInt()) {
                        scanButton.setBackgroundResource(R.drawable.scan_button_down);
                        mScanManager.startDecode();
                    } else {
                        scanButton.setBackgroundResource(R.drawable.scan_button_down);
                        mScanManager.startDecode();
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if(idmode[1] != Triggering.CONTINUOUS.toInt()) {
                        mScanManager.stopDecode();
                    }
                    scanButton.setBackgroundResource(R.drawable.scan_button);
                    break;
            }
            return true;
        });
    }

    private void setScanResult(String result){
        if(result != null) {
            barcode_result.setText(result);
            sparePartApi.getPartByMaterialNo(OnlineUser.getToken(OutScanActivity.this),result).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String resultJson = response.body().string();
                        JSONObject result = new JSONObject(resultJson);
                        int code = result.getInt("code");
                        String msg = result.getString("msg");
                        if (code == 200) {
                            new ToneGenerator(AudioManager.STREAM_SYSTEM, ToneGenerator.MAX_VOLUME).startTone(ToneGenerator.TONE_PROP_BEEP);
                            JSONObject tSparePartJson = result.getJSONObject("data");
                            name.setText(tSparePartJson.getString("name"));
                            brand.setText(tSparePartJson.getString("brand"));
                            line.setText(tSparePartJson.getString("line"));
                            station.setText(tSparePartJson.getString("station"));
                            location.setText(tSparePartJson.getString("location"));
                            specification.setText(tSparePartJson.getString("specification"));
                            stock.setText(tSparePartJson.getString("stock"));
                            unitPrice.setText(tSparePartJson.getString("unitPrice"));
                            controller.setVisibility(View.VISIBLE);
                        } else {
                            throw new RuntimeException(code + ":" + msg);
                        }
                    } catch (Exception e) {
                        reset();
                        e.printStackTrace();
                        AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                                "系统错误", e.toString(), "确认", null).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                            "系统错误", t.toString(), "确认", null).show();
                }
            });
        }
    }

    private void out(TOutWarehouseV tOutWarehouseV){
        outWarehouseApi.add(OnlineUser.getToken(OutScanActivity.this),tOutWarehouseV).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                                "系统提示", msg, "确认", null).show();
                        reset();
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mScanReceiver!=null)
            unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(uboxunMark){
            IntentFilter filter = new IntentFilter();
            action_value_buf = mScanManager.getParameterString(idbuf);
            filter.addAction(action_value_buf[0]);
            registerReceiver(mScanReceiver, filter);
        }
    }

    private void spinnerInit() {
        // 获取产线的所有选项
        equipmentApi.getProductLine(OnlineUser.getToken(OutScanActivity.this)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        List<String> lines = new ArrayList<>();
                        lines.add("【请选择】");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            lines.add(name);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(OutScanActivity.this,
                                R.layout.spinner_item, lines);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        line_spinner.setAdapter(adapter);
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });
        // 设置监听
        line_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String selected_line = (String) adapterView.getItemAtPosition(i);
                // 获取对应产线的所有工位
                equipmentApi.getStation(OnlineUser.getToken(OutScanActivity.this), selected_line).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String resultJson = response.body().string();
                            JSONObject result = new JSONObject(resultJson);
                            int code = result.getInt("code");
                            String msg = result.getString("msg");
                            if (code == 200) {
                                JSONArray jsonArrays = result.getJSONArray("rows");
                                List<String> lines = new ArrayList<>();
                                lines.add("【请选择】");
                                for (int i = 0; i < jsonArrays.length(); i++) {
                                    JSONObject jsonObject = jsonArrays.getJSONObject(i);
                                    String name = jsonObject.getString("name");
                                    String equipmentName = jsonObject.getString("value");
                                    lines.add(name+"\n"+equipmentName);

                                }
                                ArrayAdapter<String> adapter = new ArrayAdapter<String>(OutScanActivity.this,
                                        R.layout.spinner_item, lines);
                                adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
                                station_spinner.setAdapter(adapter);
                            } else {
                                throw new RuntimeException(code + ":" + msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                                    "系统错误", e.toString(), "确认", null).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                                "系统错误", t.toString(), "确认", null).show();
                    }
                });

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        // 出库类型
        equipmentApi.getOutType(OnlineUser.getToken(OutScanActivity.this)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        List<String> lines = new ArrayList<>();
                        lines.add("【请选择】");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            lines.add(name);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(OutScanActivity.this,
                                R.layout.spinner_item, lines);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        out_type_spinner.setAdapter(adapter);
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(OutScanActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });


    }


}
